package com.inspectortime.webapp.payment;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;

import com.inspectortime.domain.InspectorCompany;
import com.inspectortime.domain.billing.ConfirmedStatus;
import com.inspectortime.domain.billing.Payment;
import com.inspectortime.domain.billing.PaymentMethod;
import com.inspectortime.domain.type.PaymentStatus;
import com.inspectortime.domain.type.State;
import com.mkode.util.servlet.RequestDebugger;

/**
 * Controller for a form POST callback from Authorize.net. Note this URL is configured in the Authorize.Net merchant interface.
 * @author mkvalsvik
 *
 */
public class AuthorizeNetConfirmationCallbackResponseController extends AbstractConfirmationCallbackResponseController {

	private static Log log = LogFactory.getLog(AuthorizeNetConfirmationCallbackResponseController.class);
	
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		log.debug("Processing callback request...");

		if (!request.getMethod().equalsIgnoreCase("post")) {
			log.warn("Not a POST request: \n"
					+ RequestDebugger.requestToString(request));
			return showDefaultError();
		}

		String invoiceNumber = request.getParameter("x_invoice_num");
		if (invoiceNumber == null) {
			log.warn("Missing parameter 'x_invoice_num': \n"
					+ RequestDebugger.requestToString(request));
			return showDefaultError();
		}

		Payment payment = repository.findPaymentByInvoiceNumber(invoiceNumber);
		if (payment == null) {
			log.warn("Invoice number '" + invoiceNumber
					+ "' does not exist: \n"
					+ RequestDebugger.requestToString(request));
			return showDefaultError();
		}
		
		// Bind request to payment instance
		payment.setAmount(Double.parseDouble(request.getParameter("x_amount")));
		payment.getPayerName().setFirst(request.getParameter("x_first_name"));
		payment.getPayerName().setLast(request.getParameter("x_last_name"));
		payment.setPayerCompany(request.getParameter("x_company"));
		payment.getPayerAddress().setStreet1(request.getParameter("x_address"));
		payment.getPayerAddress().setCity(request.getParameter("x_city"));
		payment.getPayerAddress().setState(State.valueOf(request.getParameter("x_state")));
		payment.getPayerAddress().setZipCode(request.getParameter("x_zip"));
		payment.setPayerPhone(request.getParameter("x_phone"));
		payment.setPayerEmail(request.getParameter("x_email"));
		payment.setTransactionId(request.getParameter("x_trans_id"));
		String responseCode = request.getParameter("x_response_code");
		payment.setResponseCode(responseCode);
		String responseText = request.getParameter("x_response_reason_text");
		payment.setResponseText(responseText);
		if (responseCode.equals("1")) {
			payment.setConfirmedStatus(ConfirmedStatus.CONFIRMED);
			updatePaymentSourceStatus(payment, PaymentStatus.PAID_AUTHNET);
		} else {
			payment.setConfirmedStatus(ConfirmedStatus.DECLINED);
			updatePaymentSourceStatus(payment, PaymentStatus.NOT_PAID);
		}
		payment.setPaymentMethod(PaymentMethod.AUTHORIZE_NET);
		payment.save();

		InspectorCompany company = this.lookupCompany(payment);
		
		// Render view
		ModelAndView mv = new ModelAndView(
				"payment/processorConfirmationCallbackResponse");
		mv.addObject("inspectorCompany", company);
		mv.addObject("payment", payment);
		return mv;
	}
}
